home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 17 / CU Amiga Magazine's Super CD-ROM 17 (1997)(EMAP Images)(GB)[!][issue 1997-12].iso / CUCD / Programming / Make / source / main.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-09-24  |  65.1 KB  |  2,405 lines

  1. /* Argument parsing and main program of GNU Make.
  2. Copyright (C) 1988,89,90,91,94,95,96,97 Free Software Foundation, Inc.
  3. This file is part of GNU Make.
  4.  
  5. GNU Make is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. GNU Make is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. GNU General Public License for more details.
  14.  
  15. You should have received a copy of the GNU General Public License
  16. along with GNU Make; see the file COPYING.  If not, write to
  17. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. #include "make.h"
  20. #include "dep.h"
  21. #include "filedef.h"
  22. #include "variable.h"
  23. #include "job.h"
  24. #include "commands.h"
  25. #include "getopt.h"
  26. #include <assert.h>
  27. #ifdef WINDOWS32
  28. #include <windows.h>
  29. #include "pathstuff.h"
  30. #endif
  31.  
  32. extern void init_dir PARAMS ((void));
  33. extern void remote_setup PARAMS ((void));
  34. extern void remote_cleanup PARAMS ((void));
  35. extern RETSIGTYPE fatal_error_signal PARAMS ((int sig));
  36. extern RETSIGTYPE child_handler PARAMS ((int sig));
  37.  
  38. extern void print_variable_data_base PARAMS ((void));
  39. extern void print_dir_data_base PARAMS ((void));
  40. extern void print_rule_data_base PARAMS ((void));
  41. extern void print_file_data_base PARAMS ((void));
  42. extern void print_vpath_data_base PARAMS ((void));
  43.  
  44. #ifdef _AMIGA
  45. extern void amiga_startup PARAMS ((int *argc,char ***argv));
  46. extern void amiga_set_makelevel PARAMS ((unsigned int));
  47. extern void amiga_get_global_env PARAMS ((void));
  48. #endif
  49.  
  50. #ifndef    HAVE_UNISTD_H
  51. extern int chdir ();
  52. #endif
  53. #ifndef    STDC_HEADERS
  54. #ifndef    sun            /* Sun has an incorrect decl in a header.  */
  55. extern void exit ();
  56. #endif
  57. extern double atof ();
  58. #endif
  59. extern char *mktemp ();
  60.  
  61. static void print_data_base PARAMS((void));
  62. static void print_version PARAMS ((void));
  63. static void decode_switches PARAMS ((int argc, char **argv, int env));
  64. static void decode_env_switches PARAMS ((char *envar, unsigned int len));
  65. static void define_makeflags PARAMS ((int all, int makefile));
  66. static char *quote_as_word PARAMS ((char *out, char *in, int double_dollars));
  67.  
  68. /* The structure that describes an accepted command switch.  */
  69.  
  70. struct command_switch
  71.   {
  72.     char c;            /* The switch character.  */
  73.  
  74.     enum            /* Type of the value.  */
  75.       {
  76.     flag,            /* Turn int flag on.  */
  77.     flag_off,        /* Turn int flag off.  */
  78.     string,            /* One string per switch.  */
  79.     positive_int,        /* A positive integer.  */
  80.     floating,        /* A floating-point number (double).  */
  81.     ignore            /* Ignored.  */
  82.       } type;
  83.  
  84.     char *value_ptr;    /* Pointer to the value-holding variable.  */
  85.  
  86.     unsigned int env:1;        /* Can come from MAKEFLAGS.  */
  87.     unsigned int toenv:1;    /* Should be put in MAKEFLAGS.  */
  88.     unsigned int no_makefile:1;    /* Don't propagate when remaking makefiles.  */
  89.  
  90.     char *noarg_value;    /* Pointer to value used if no argument is given.  */
  91.     char *default_value;/* Pointer to default value.  */
  92.  
  93.     char *long_name;        /* Long option name.  */
  94.     char *argdesc;        /* Descriptive word for argument.  */
  95.     char *description;        /* Description for usage message.  */
  96.   };
  97.  
  98.  
  99. /* The structure used to hold the list of strings given
  100.    in command switches of a type that takes string arguments.  */
  101.  
  102. struct stringlist
  103.   {
  104.     char **list;    /* Nil-terminated list of strings.  */
  105.     unsigned int idx;    /* Index into above.  */
  106.     unsigned int max;    /* Number of pointers allocated.  */
  107.   };
  108.  
  109.  
  110. /* The recognized command switches.  */
  111.  
  112. /* Nonzero means do not print commands to be executed (-s).  */
  113.  
  114. int silent_flag;
  115.  
  116. /* Nonzero means just touch the files
  117.    that would appear to need remaking (-t)  */
  118.  
  119. int touch_flag;
  120.  
  121. /* Nonzero means just print what commands would need to be executed,
  122.    don't actually execute them (-n).  */
  123.  
  124. int just_print_flag;
  125.  
  126. /* Print debugging trace info (-d).  */
  127.  
  128. int debug_flag = 0;
  129.  
  130. #ifdef WINDOWS32
  131. /* Suspend make in main for a short time to allow debugger to attach */
  132.  
  133. int suspend_flag = 0;
  134. #endif
  135.  
  136. /* Environment variables override makefile definitions.  */
  137.  
  138. int env_overrides = 0;
  139.  
  140. /* Nonzero means ignore status codes returned by commands
  141.    executed to remake files.  Just treat them all as successful (-i).  */
  142.  
  143. int ignore_errors_flag = 0;
  144.  
  145. /* Nonzero means don't remake anything, just print the data base
  146.    that results from reading the makefile (-p).  */
  147.  
  148. int print_data_base_flag = 0;
  149.  
  150. /* Nonzero means don't remake anything; just return a nonzero status
  151.    if the specified targets are not up to date (-q).  */
  152.  
  153. int question_flag = 0;
  154.  
  155. /* Nonzero means do not use any of the builtin rules (-r).  */
  156.  
  157. int no_builtin_rules_flag = 0;
  158.  
  159. /* Nonzero means keep going even if remaking some file fails (-k).  */
  160.  
  161. int keep_going_flag;
  162. int default_keep_going_flag = 0;
  163.  
  164. /* Nonzero means print directory before starting and when done (-w).  */
  165.  
  166. int print_directory_flag = 0;
  167.  
  168. /* Nonzero means ignore print_directory_flag and never print the directory.
  169.    This is necessary because print_directory_flag is set implicitly.  */
  170.  
  171. int inhibit_print_directory_flag = 0;
  172.  
  173. /* Nonzero means print version information.  */
  174.  
  175. int print_version_flag = 0;
  176.  
  177. /* List of makefiles given with -f switches.  */
  178.  
  179. static struct stringlist *makefiles = 0;
  180.  
  181.  
  182. /* Number of job slots (commands that can be run at once).  */
  183.  
  184. unsigned int job_slots = 1;
  185. unsigned int default_job_slots = 1;
  186.  
  187. /* Value of job_slots that means no limit.  */
  188.  
  189. static unsigned int inf_jobs = 0;
  190.  
  191. /* Maximum load average at which multiple jobs will be run.
  192.    Negative values mean unlimited, while zero means limit to
  193.    zero load (which could be useful to start infinite jobs remotely
  194.    but one at a time locally).  */
  195. #ifndef NO_FLOAT
  196. double max_load_average = -1.0;
  197. double default_load_average = -1.0;
  198. #else
  199. int max_load_average = -1;
  200. int default_load_average = -1;
  201. #endif
  202.  
  203. /* List of directories given with -C switches.  */
  204.  
  205. static struct stringlist *directories = 0;
  206.  
  207. /* List of include directories given with -I switches.  */
  208.  
  209. static struct stringlist *include_directories = 0;
  210.  
  211. /* List of files given with -o switches.  */
  212.  
  213. static struct stringlist *old_files = 0;
  214.  
  215. /* List of files given with -W switches.  */
  216.  
  217. static struct stringlist *new_files = 0;
  218.  
  219. /* If nonzero, we should just print usage and exit.  */
  220.  
  221. static int print_usage_flag = 0;
  222.  
  223. /* If nonzero, we should print a warning message
  224.    for each reference to an undefined variable.  */
  225.  
  226. int warn_undefined_variables_flag;
  227.  
  228. /* The table of command switches.  */
  229.  
  230. static const struct command_switch switches[] =
  231.   {
  232.     { 'b', ignore, 0, 0, 0, 0, 0, 0,
  233.     0, 0,
  234.     "Ignored for compatibility" },
  235.     { 'C', string, (char *) &directories, 0, 0, 0, 0, 0,
  236.     "directory", "DIRECTORY",
  237.     "Change to DIRECTORY before doing anything" },
  238.     { 'd', flag, (char *) &debug_flag, 1, 1, 0, 0, 0,
  239.     "debug", 0,
  240.     "Print lots of debugging information" },
  241. #ifdef WINDOWS32
  242.     { 'D', flag, (char *) &suspend_flag, 1, 1, 0, 0, 0,
  243.         "suspend-for-debug", 0,
  244.         "Suspend process to allow a debugger to attach" },
  245. #endif
  246.     { 'e', flag, (char *) &env_overrides, 1, 1, 0, 0, 0,
  247.     "environment-overrides", 0,
  248.     "Environment variables override makefiles" },
  249.     { 'f', string, (char *) &makefiles, 0, 0, 0, 0, 0,
  250.     "file", "FILE",
  251.     "Read FILE as a makefile" },
  252.     { 'h', flag, (char *) &print_usage_flag, 0, 0, 0, 0, 0,
  253.     "help", 0,
  254.     "Print this message and exit" },
  255.     { 'i', flag, (char *) &ignore_errors_flag, 1, 1, 0, 0, 0,
  256.     "ignore-errors", 0,
  257.     "Ignore errors from commands" },
  258.     { 'I', string, (char *) &include_directories, 1, 1, 0, 0, 0,
  259.     "include-dir", "DIRECTORY",
  260.     "Search DIRECTORY for included makefiles" },
  261.     { 'j', positive_int, (char *) &job_slots, 1, 1, 0,
  262.     (char *) &inf_jobs, (char *) &default_job_slots,
  263.     "jobs", "N",
  264.     "Allow N jobs at once; infinite jobs with no arg" },
  265.     { 'k', flag, (char *) &keep_going_flag, 1, 1, 0,
  266.     0, (char *) &default_keep_going_flag,
  267.     "keep-going", 0,
  268.     "Keep going when some targets can't be made" },
  269. #ifndef NO_FLOAT
  270.     { 'l', floating, (char *) &max_load_average, 1, 1, 0,
  271.     (char *) &default_load_average, (char *) &default_load_average,
  272.     "load-average", "N",
  273.     "Don't start multiple jobs unless load is below N" },
  274. #else
  275.     { 'l', positive_int, (char *) &max_load_average, 1, 1, 0,
  276.     (char *) &default_load_average, (char *) &default_load_average,
  277.     "load-average", "N",
  278.     "Don't start multiple jobs unless load is below N" },
  279. #endif
  280.     { 'm', ignore, 0, 0, 0, 0, 0, 0,
  281.     0, 0,
  282.     "-b" },
  283.     { 'n', flag, (char *) &just_print_flag, 1, 1, 1, 0, 0,
  284.     "just-print", 0,
  285.     "Don't actually run any commands; just print them" },
  286.     { 'o', string, (char *) &old_files, 0, 0, 0, 0, 0,
  287.     "old-file", "FILE",
  288.     "Consider FILE to be very old and don't remake it" },
  289.     { 'p', flag, (char *) &print_data_base_flag, 1, 1, 0, 0, 0,
  290.     "print-data-base", 0,
  291.     "Print make's internal database" },
  292.     { 'q', flag, (char *) &question_flag, 1, 1, 1, 0, 0,
  293.     "question", 0,
  294.     "Run no commands; exit status says if up to date" },
  295.     { 'r', flag, (char *) &no_builtin_rules_flag, 1, 1, 0, 0, 0,
  296.     "no-builtin-rules", 0,
  297.     "Disable the built-in implicit rules" },
  298.     { 's', flag, (char *) &silent_flag, 1, 1, 0, 0, 0,
  299.     "silent", 0,
  300.     "Don't echo commands" },
  301.     { 'S', flag_off, (char *) &keep_going_flag, 1, 1, 0,
  302.     0, (char *) &default_keep_going_flag,
  303.     "no-keep-going", 0,
  304.     "Turns off -k" },
  305.     { 't', flag, (char *) &touch_flag, 1, 1, 1, 0, 0,
  306.     "touch", 0,
  307.     "Touch targets instead of remaking them" },
  308.     { 'v', flag, (char *) &print_version_flag, 1, 1, 0, 0, 0,
  309.     "version", 0,
  310.     "Print the version number of make and exit" },
  311.     { 'w', flag, (char *) &print_directory_flag, 1, 1, 0, 0, 0,
  312.     "print-directory", 0,
  313.     "Print the current directory" },
  314.     { 2, flag, (char *) &inhibit_print_directory_flag, 1, 1, 0, 0, 0,
  315.     "no-print-directory", 0,
  316.     "Turn off -w, even if it was turned on implicitly" },
  317.     { 'W', string, (char *) &new_files, 0, 0, 0, 0, 0,
  318.     "what-if", "FILE",
  319.     "Consider FILE to be infinitely new" },
  320.     { 3, flag, (char *) &warn_undefined_variables_flag, 1, 1, 0, 0, 0,
  321.     "warn-undefined-variables", 0,
  322.     "Warn when an undefined variable is referenced" },
  323.     { '\0', }
  324.   };
  325.  
  326. /* Secondary long names for options.  */
  327.  
  328. static struct option long_option_aliases[] =
  329.   {
  330.     { "quiet",        no_argument,        0, 's' },
  331.     { "stop",        no_argument,        0, 'S' },
  332.     { "new-file",    required_argument,    0, 'W' },
  333.     { "assume-new",    required_argument,    0, 'W' },
  334.     { "assume-old",    required_argument,    0, 'o' },
  335.     { "max-load",    optional_argument,    0, 'l' },
  336.     { "dry-run",    no_argument,        0, 'n' },
  337.     { "recon",        no_argument,        0, 'n' },
  338.     { "makefile",    required_argument,    0, 'f' },
  339.   };
  340.  
  341. /* The usage message prints the descriptions of options starting in
  342.    this column.  Make sure it leaves enough room for the longest
  343.    description to fit in less than 80 characters.  */
  344.  
  345. #define    DESCRIPTION_COLUMN    30
  346.  
  347. /* List of goal targets.  */
  348.  
  349. static struct dep *goals, *lastgoal;
  350.  
  351. /* List of variables which were defined on the command line
  352.    (or, equivalently, in MAKEFLAGS).  */
  353.  
  354. struct command_variable
  355.   {
  356.     struct command_variable *next;
  357.     struct variable *variable;
  358.   };
  359. static struct command_variable *command_variables;
  360.  
  361. /* The name we were invoked with.  */
  362.  
  363. char *program;
  364.  
  365. /* Our current directory before processing any -C options.  */
  366.  
  367. char *directory_before_chdir;
  368.  
  369. /* Our current directory after processing all -C options.  */
  370.  
  371. char *starting_directory;
  372.  
  373. /* Value of the MAKELEVEL variable at startup (or 0).  */
  374.  
  375. unsigned int makelevel;
  376.  
  377. /* First file defined in the makefile whose name does not
  378.    start with `.'.  This is the default to remake if the
  379.    command line does not specify.  */
  380.  
  381. struct file *default_goal_file;
  382.  
  383. /* Pointer to structure for the file .DEFAULT
  384.    whose commands are used for any file that has none of its own.
  385.    This is zero if the makefiles do not define .DEFAULT.  */
  386.  
  387. struct file *default_file;
  388.  
  389. /* Nonzero if we have seen the magic `.POSIX' target.
  390.    This turns on pedantic compliance with POSIX.2.  */
  391.  
  392. int posix_pedantic;
  393.  
  394. /* Nonzero if some rule detected clock skew; we keep track so (a) we only
  395.    print one warning about it during the run, and (b) we can print a final
  396.    warning at the end of the run. */
  397.  
  398. int clock_skew_detected;
  399.  
  400. /* Mask of signals that are being caught with fatal_error_signal.  */
  401.  
  402. #ifdef    POSIX
  403. sigset_t fatal_signal_set;
  404. #else
  405. #ifdef    HAVE_SIGSETMASK
  406. int fatal_signal_mask;
  407. #endif
  408. #endif
  409.  
  410. static struct file *
  411. enter_command_line_file (name)
  412.      char *name;
  413. {
  414.   if (name[0] == '\0')
  415.     fatal ("empty string invalid as file name");
  416.  
  417.   if (name[0] == '~')
  418.     {
  419.       char *expanded = tilde_expand (name);
  420.       if (expanded != 0)
  421.     name = expanded;    /* Memory leak; I don't care.  */
  422.     }
  423.  
  424.   /* This is also done in parse_file_seq, so this is redundant
  425.      for names read from makefiles.  It is here for names passed
  426.      on the command line.  */
  427.   while (name[0] == '.' && name[1] == '/' && name[2] != '\0')
  428.     {
  429.       name += 2;
  430.       while (*name == '/')
  431.     /* Skip following slashes: ".//foo" is "foo", not "/foo".  */
  432.     ++name;
  433.     }
  434.  
  435.   if (*name == '\0')
  436.     {
  437.       /* It was all slashes!  Move back to the dot and truncate
  438.      it after the first slash, so it becomes just "./".  */
  439.       do
  440.     --name;
  441.       while (name[0] != '.');
  442.       name[2] = '\0';
  443.     }
  444.  
  445.   return enter_file (savestring (name, strlen (name)));
  446. }
  447.  
  448. /* Toggle -d on receipt of SIGUSR1.  */
  449.  
  450. static RETSIGTYPE
  451. debug_signal_handler (sig)
  452.      int sig;
  453. {
  454.   debug_flag = ! debug_flag;
  455. }
  456.  
  457. #ifdef WINDOWS32
  458. /*
  459.  * HANDLE runtime exceptions by avoiding a requestor on the GUI. Capture
  460.  * exception and print it to stderr instead.
  461.  *
  462.  * If debug_flag not set, just print a simple message and exit.
  463.  * If debug_flag set, print a more verbose message.
  464.  * If compiled for DEBUG, let exception pass through to GUI so that
  465.  *   debuggers can attach.
  466.  */
  467. LONG WINAPI
  468. handle_runtime_exceptions( struct _EXCEPTION_POINTERS *exinfo )
  469. {
  470.   PEXCEPTION_RECORD exrec = exinfo->ExceptionRecord;
  471.   LPSTR cmdline = GetCommandLine();
  472.   LPSTR prg = strtok(cmdline, " ");
  473.   CHAR errmsg[1024];
  474. #ifdef USE_EVENT_LOG
  475.   HANDLE hEventSource;
  476.   LPTSTR lpszStrings[1];
  477. #endif
  478.  
  479.   if (!debug_flag)
  480.     {
  481.       sprintf(errmsg, "%s: Interrupt/Exception caught ", prg);
  482.       sprintf(&errmsg[strlen(errmsg)],
  483.               "(code = 0x%x, addr = 0x%x)\r\n",
  484.               exrec->ExceptionCode, exrec->ExceptionAddress);
  485.       fprintf(stderr, errmsg);
  486.       exit(255);
  487.     }
  488.  
  489.   sprintf(errmsg,
  490.           "\r\nUnhandled exception filter called from program %s\r\n", prg);
  491.   sprintf(&errmsg[strlen(errmsg)], "ExceptionCode = %x\r\n",
  492.           exrec->ExceptionCode);
  493.   sprintf(&errmsg[strlen(errmsg)], "ExceptionFlags = %x\r\n",
  494.           exrec->ExceptionFlags);
  495.   sprintf(&errmsg[strlen(errmsg)], "ExceptionAddress = %x\r\n",
  496.           exrec->ExceptionAddress);
  497.  
  498.   if (exrec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION
  499.       && exrec->NumberParameters >= 2)
  500.     sprintf(&errmsg[strlen(errmsg)],
  501.             "Access violation: %s operation at address %x\r\n",
  502.             exrec->ExceptionInformation[0] ? "write": "read",
  503.             exrec->ExceptionInformation[1]);
  504.  
  505.   /* turn this on if we want to put stuff in the event log too */
  506. #ifdef USE_EVENT_LOG
  507.   hEventSource = RegisterEventSource(NULL, "GNU Make");
  508.   lpszStrings[0] = errmsg;
  509.  
  510.   if (hEventSource != NULL)
  511.     {
  512.       ReportEvent(hEventSource,         /* handle of event source */
  513.                   EVENTLOG_ERROR_TYPE,  /* event type */
  514.                   0,                    /* event category */
  515.                   0,                    /* event ID */
  516.                   NULL,                 /* current user's SID */
  517.                   1,                    /* strings in lpszStrings */
  518.                   0,                    /* no bytes of raw data */
  519.                   lpszStrings,          /* array of error strings */
  520.                   NULL);                /* no raw data */
  521.  
  522.       (VOID) DeregisterEventSource(hEventSource);
  523.     }
  524. #endif
  525.  
  526.   /* Write the error to stderr too */
  527.   fprintf(stderr, errmsg);
  528.  
  529. #ifdef DEBUG
  530.   return EXCEPTION_CONTINUE_SEARCH;
  531. #else
  532.   exit(255);
  533. #endif
  534. }
  535. #endif  /* WINDOWS32 */
  536.  
  537. #ifdef  __MSDOS__
  538.  
  539. static void
  540. msdos_return_to_initial_directory ()
  541. {
  542.   if (directory_before_chdir)
  543.     chdir (directory_before_chdir);
  544. }
  545. #endif
  546.  
  547. #ifndef _AMIGA
  548. int
  549. main (argc, argv, envp)
  550.      int argc;
  551.      char **argv;
  552.      char **envp;
  553. #else
  554. int main (int argc, char ** argv)
  555. #endif
  556. {
  557.   register struct file *f;
  558.   register unsigned int i;
  559.   char **p;
  560.   struct dep *read_makefiles;
  561.   PATH_VAR (current_directory);
  562. #ifdef WINDOWS32
  563.   extern int no_default_sh_exe;
  564.   char *unix_path = NULL;
  565.   char *windows32_path = NULL;
  566.  
  567.   SetUnhandledExceptionFilter(handle_runtime_exceptions);
  568. #endif
  569.  
  570.   default_goal_file = 0;
  571.   reading_filename = 0;
  572.   reading_lineno_ptr = 0;
  573.  
  574. #if defined (__MSDOS__) && !defined (_POSIX_SOURCE)
  575.   /* Request the most powerful version of `system', to
  576.      make up for the dumb default shell.  */
  577.   __system_flags = (__system_redirect
  578.             | __system_use_shell
  579.             | __system_allow_multiple_cmds
  580.             | __system_allow_long_cmds
  581.             | __system_handle_null_commands
  582.             | __system_emulate_chdir);
  583.  
  584. #endif
  585.  
  586. #if !defined (HAVE_STRSIGNAL) && !defined (HAVE_SYS_SIGLIST)
  587.   signame_init ();
  588. #endif
  589.  
  590. #ifdef    POSIX
  591.   sigemptyset (&fatal_signal_set);
  592. #define    ADD_SIG(sig)    sigaddset (&fatal_signal_set, sig)
  593. #else
  594. #ifdef    HAVE_SIGSETMASK
  595.   fatal_signal_mask = 0;
  596. #define    ADD_SIG(sig)    fatal_signal_mask |= sigmask (sig)
  597. #else
  598. #define    ADD_SIG(sig)
  599. #endif
  600. #endif
  601.  
  602. #define    FATAL_SIG(sig)                                  \
  603.   if (signal ((sig), fatal_error_signal) == SIG_IGN)                  \
  604.     (void) signal ((sig), SIG_IGN);                          \
  605.   else                                          \
  606.     ADD_SIG (sig);
  607.  
  608. #ifdef SIGHUP
  609.   FATAL_SIG (SIGHUP);
  610. #endif
  611. #ifdef SIGQUIT
  612.   FATAL_SIG (SIGQUIT);
  613. #endif
  614.   FATAL_SIG (SIGINT);
  615.   FATAL_SIG (SIGTERM);
  616.  
  617. #ifdef    SIGDANGER
  618.   FATAL_SIG (SIGDANGER);
  619. #endif
  620. #ifdef SIGXCPU
  621.   FATAL_SIG (SIGXCPU);
  622. #endif
  623. #ifdef SIGXFSZ
  624.   FATAL_SIG (SIGXFSZ);
  625. #endif
  626.  
  627. #undef    FATAL_SIG
  628.  
  629.   /* Make sure stdout is line-buffered.  */
  630.  
  631. #ifdef    HAVE_SETLINEBUF
  632.   setlinebuf (stdout);
  633. #else
  634. #ifndef    SETVBUF_REVERSED
  635.   setvbuf (stdout, (char *) 0, _IOLBF, BUFSIZ);
  636. #else    /* setvbuf not reversed.  */
  637.   /* Some buggy systems lose if we pass 0 instead of allocating ourselves.  */
  638.   setvbuf (stdout, _IOLBF, xmalloc (BUFSIZ), BUFSIZ);
  639. #endif    /* setvbuf reversed.  */
  640. #endif    /* setlinebuf missing.  */
  641.  
  642. #ifdef _AMIGA
  643.   /* support of the workbench (desktop) startup */
  644.   amiga_startup(&argc,&argv);
  645. #endif
  646.  
  647.   /* Figure out where this program lives.  */
  648.  
  649.   if (argv[0] == 0)
  650.     argv[0] = "";
  651.   if (argv[0][0] == '\0')
  652.     program = "make";
  653.   else
  654.     {
  655. #ifdef VMS
  656.       program = rindex (argv[0], ']');
  657. #else
  658.       program = rindex (argv[0], '/');
  659. #endif
  660. #ifdef __MSDOS__
  661.       if (program == 0)
  662.     program = rindex (argv[0], '\\');
  663.       else
  664.     {
  665.       /* Some weird environments might pass us argv[0] with
  666.          both kinds of slashes; we must find the rightmost.  */
  667.       char *p = rindex (argv[0], '\\');
  668.       if (p && p > program)
  669.         program = p;
  670.     }
  671.       if (program == 0 && argv[0][1] == ':')
  672.     program = argv[0] + 1;
  673. #endif
  674.       if (program == 0)
  675.     program = argv[0];
  676.       else
  677.     ++program;
  678.     }
  679.  
  680.   /* Set up to access user data (files).  */
  681.   user_access ();
  682.  
  683.   /* Figure out where we are.  */
  684.  
  685. #ifdef WINDOWS32
  686.   if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
  687. #else
  688.   if (getcwd (current_directory, GET_PATH_MAX) == 0)
  689. #endif
  690.     {
  691. #ifdef    HAVE_GETCWD
  692.       perror_with_name ("getcwd: ", "");
  693. #else
  694.       error ("getwd: %s", current_directory);
  695. #endif
  696.       current_directory[0] = '\0';
  697.       directory_before_chdir = 0;
  698.     }
  699.   else
  700.     directory_before_chdir = savestring (current_directory,
  701.                      strlen (current_directory));
  702. #ifdef  __MSDOS__
  703.   /* Make sure we will return to the initial directory, come what may.  */
  704.   atexit (msdos_return_to_initial_directory);
  705. #endif
  706.  
  707.   /* Read in variables from the environment.  It is important that this be
  708.      done before $(MAKE) is figured out so its definitions will not be
  709.      from the environment.  */
  710.  
  711. #ifndef _AMIGA
  712.   for (i = 0; envp[i] != 0; ++i)
  713.     {
  714.       register char *ep = envp[i];
  715.       while (*ep != '=')
  716.     ++ep;
  717. #ifdef WINDOWS32
  718.       if (!unix_path && !strncmp(envp[i], "PATH=", 5))
  719.         unix_path = ep+1;
  720.       if (!windows32_path && !strncmp(envp[i], "Path=", 5))
  721.         windows32_path = ep+1;
  722. #endif
  723.       /* The result of pointer arithmetic is cast to unsigned int for
  724.      machines where ptrdiff_t is a different size that doesn't widen
  725.      the same.  */
  726.       define_variable (envp[i], (unsigned int) (ep - envp[i]),
  727.                ep + 1, o_env, 1)
  728.     /* Force exportation of every variable culled from the environment.
  729.        We used to rely on target_environment's v_default code to do this.
  730.        But that does not work for the case where an environment variable
  731.        is redefined in a makefile with `override'; it should then still
  732.        be exported, because it was originally in the environment.  */
  733.     ->export = v_export;
  734.     }
  735. #ifdef WINDOWS32
  736.     /*
  737.      * PATH defaults to Path iff PATH not found and Path is found.
  738.      */
  739.     if (!unix_path && windows32_path)
  740.       define_variable("PATH", 4, windows32_path, o_env, 1)->export = v_export;
  741. #endif
  742. #else /* For Amiga, read the ENV: device, ignoring all dirs */
  743.     {
  744.     amiga_get_global_env();
  745.     }
  746. #endif
  747.  
  748.   /* Decode the switches.  */
  749.  
  750.   decode_env_switches ("MAKEFLAGS", 9);
  751. #if 0
  752.   /* People write things like:
  753.          MFLAGS="CC=gcc -pipe" "CFLAGS=-g"
  754.      and we set the -p, -i and -e switches.  Doesn't seem quite right.  */
  755.   decode_env_switches ("MFLAGS", 6);
  756. #endif
  757.   decode_switches (argc, argv, 0);
  758. #ifdef WINDOWS32
  759.   if (suspend_flag) {
  760.         fprintf(stderr, "%s (pid = %d)\n", argv[0], GetCurrentProcessId());
  761.         fprintf(stderr, "%s is suspending for 30 seconds...", argv[0]);
  762.         Sleep(30 * 1000);
  763.         fprintf(stderr, "done sleep(30). Continuing.\n");
  764.   }
  765. #endif
  766.  
  767.   /* Print version information.  */
  768.  
  769.   if (print_version_flag || print_data_base_flag || debug_flag)
  770.     print_version ();
  771.  
  772.   /* `make --version' is supposed to just print the version and exit.  */
  773.   if (print_version_flag)
  774.     die (0);
  775.  
  776. #if !defined(__MSDOS__) && !defined(VMS)
  777.   /* Set the "MAKE_COMMAND" variable to the name we were invoked with.
  778.      (If it is a relative pathname with a slash, prepend our directory name
  779.      so the result will run the same program regardless of the current dir.
  780.      If it is a name with no slash, we can only hope that PATH did not
  781.      find it in the current directory.)  */
  782. #ifdef WINDOWS32
  783.   /*
  784.    * Convert from backslashes to forward slashes for
  785.    * programs like sh which don't like them. Shouldn't
  786.    * matter if the path is one way or the other for
  787.    * CreateProcess().
  788.    */
  789.   if (strpbrk(argv[0], "/:\\") ||
  790.       strstr(argv[0], "..") ||
  791.       !strncmp(argv[0], "//", 2))
  792.     argv[0] = strdup(w32ify(argv[0],1));
  793. #else /* WINDOWS32 */
  794.   if (current_directory[0] != '\0'
  795.       && argv[0] != 0 && argv[0][0] != '/' && index (argv[0], '/') != 0)
  796.     argv[0] = concat (current_directory, "/", argv[0]);
  797. #endif /* WINDOWS32 */
  798. #endif
  799.  
  800.   /* The extra indirection through $(MAKE_COMMAND) is done
  801.      for hysterical raisins.  */
  802.   (void) define_variable ("MAKE_COMMAND", 12, argv[0], o_default, 0);
  803.   (void) define_variable ("MAKE", 4, "$(MAKE_COMMAND)", o_default, 1);
  804.  
  805.   if (command_variables != 0)
  806.     {
  807.       struct command_variable *cv;
  808.       struct variable *v;
  809.       unsigned int len = 0;
  810.       char *value, *p;
  811.  
  812.       /* Figure out how much space will be taken up by the command-line
  813.      variable definitions.  */
  814.       for (cv = command_variables; cv != 0; cv = cv->next)
  815.     {
  816.       v = cv->variable;
  817.       len += 2 * strlen (v->name);
  818.       if (! v->recursive)
  819.         ++len;
  820.       ++len;
  821.       len += 2 * strlen (v->value);
  822.     }
  823.  
  824.       /* Now allocate a buffer big enough and fill it.  */
  825.       p = value = (char *) alloca (len);
  826.       for (cv = command_variables; cv != 0; cv = cv->next)
  827.     {
  828.       v = cv->variable;
  829.       p = quote_as_word (p, v->name, 0);
  830.       if (! v->recursive)
  831.         *p++ = ':';
  832.       *p++ = '=';
  833.       p = quote_as_word (p, v->value, 0);
  834.       *p++ = ' ';
  835.     }
  836.       p[-1] = '\0';        /* Kill the final space and terminate.  */
  837.  
  838.       /* Define an unchangeable variable with a name that no POSIX.2
  839.      makefile could validly use for its own variable.  */
  840.       (void) define_variable ("-*-command-variables-*-", 23,
  841.                   value, o_automatic, 0);
  842.  
  843.       /* Define the variable; this will not override any user definition.
  844.          Normally a reference to this variable is written into the value of
  845.          MAKEFLAGS, allowing the user to override this value to affect the
  846.          exported value of MAKEFLAGS.  In POSIX-pedantic mode, we cannot
  847.          allow the user's setting of MAKEOVERRIDES to affect MAKEFLAGS, so
  848.          a reference to this hidden variable is written instead. */
  849.       (void) define_variable ("MAKEOVERRIDES", 13,
  850.                   "${-*-command-variables-*-}", o_env, 1);
  851.     }
  852.  
  853.   /* If there were -C flags, move ourselves about.  */
  854.   if (directories != 0)
  855.     for (i = 0; directories->list[i] != 0; ++i)
  856.       {
  857.     char *dir = directories->list[i];
  858.     if (dir[0] == '~')
  859.       {
  860.         char *expanded = tilde_expand (dir);
  861.         if (expanded != 0)
  862.           dir = expanded;
  863.       }
  864.     if (chdir (dir) < 0)
  865.       pfatal_with_name (dir);
  866.     if (dir != directories->list[i])
  867.       free (dir);
  868.       }
  869.  
  870. #ifdef WINDOWS32
  871.   /*
  872.    * THIS BLOCK OF CODE MUST COME AFTER chdir() CALL ABOVE IN ORDER
  873.    * TO NOT CONFUSE THE DEPENDENCY CHECKING CODE IN implicit.c.
  874.    *
  875.    * The functions in dir.c can incorrectly cache information for "."
  876.    * before we have changed directory and this can cause file
  877.    * lookups to fail because the current directory (.) was pointing
  878.    * at the wrong place when it was first evaluated.
  879.    */
  880.  
  881.   /*
  882.    * On Windows/NT, we don't have the luxury of a /bin directory that
  883.    * is mapped globally to every drive mounted to the system. Since make could
  884.    * be invoked from any drive, and we don't want to propogate /bin/sh
  885.    * to every single drive. Allow ourselves a chance to search for
  886.    * a value for default shell here (if the default path does not exist).
  887.    *
  888.    * The value of default_shell is set here, but it could get reset after
  889.    * the Makefiles are read in. See logic below where SHELL is checked
  890.    * after the call to read_all_makefiles() completes.
  891.    *
  892.    * The reason SHELL is set here is so that macros can be safely evaluated
  893.    * as makefiles are read in (some macros require $SHELL).
  894.    */
  895.  
  896.   {
  897.     extern char *default_shell;
  898.  
  899.     if (!file_exists_p(default_shell)) {
  900.       char *p;
  901.       struct variable *v = lookup_variable ("Path", 4);
  902.  
  903.       /*
  904.        * Try and make sure we have a full path to default_shell before
  905.        * we parse makefiles.
  906.        */
  907.       if (v && v->value) {
  908.         PATH_VAR(sh_path);
  909.         char *ep;
  910.  
  911.         p  = v->value;
  912.         ep = strchr(p, PATH_SEPARATOR_CHAR);
  913.  
  914.         while (ep && *ep) {
  915.           *ep = '\0';
  916.  
  917.           if (dir_file_exists_p(p, default_shell)) {
  918.             sprintf(sh_path, "%s/%s", p, default_shell);
  919.             default_shell = strdup(w32ify(sh_path,0));
  920.             no_default_sh_exe = 0;
  921.             *ep = PATH_SEPARATOR_CHAR;
  922.  
  923.             /* terminate loop */
  924.             p += strlen(p);
  925.           } else {
  926.             *ep = PATH_SEPARATOR_CHAR;
  927.              p = ++ep;
  928.           }
  929.  
  930.           ep = strchr(p, PATH_SEPARATOR_CHAR);
  931.         }
  932.  
  933.         /* be sure to check last element of Path */
  934.         if (p && *p && dir_file_exists_p(p, default_shell)) {
  935.             sprintf(sh_path, "%s/%s", p, default_shell);
  936.             default_shell = strdup(w32ify(sh_path,0));
  937.             no_default_sh_exe = 0;
  938.         }
  939.       }
  940.     }
  941.   }
  942. #endif /* WINDOWS32 */
  943.   /* Figure out the level of recursion.  */
  944.   {
  945.     struct variable *v = lookup_variable ("MAKELEVEL", 9);
  946.     if (v != 0 && *v->value != '\0' && *v->value != '-')
  947.       makelevel = (unsigned int) atoi (v->value);
  948.     else
  949.       makelevel = 0;
  950.   }
  951.  
  952.   /* Except under -s, always do -w in sub-makes and under -C.  */
  953.   if (!silent_flag && (directories != 0 || makelevel > 0))
  954.     print_directory_flag = 1;
  955.  
  956.   /* Let the user disable that with --no-print-directory.  */
  957.   if (inhibit_print_directory_flag)
  958.     print_directory_flag = 0;
  959.  
  960.   /* Construct the list of include directories to search.  */
  961.  
  962.   construct_include_path (include_directories == 0 ? (char **) 0
  963.               : include_directories->list);
  964.  
  965.   /* Figure out where we are now, after chdir'ing.  */
  966.   if (directories == 0)
  967.     /* We didn't move, so we're still in the same place.  */
  968.     starting_directory = current_directory;
  969.   else
  970.     {
  971. #ifdef WINDOWS32
  972.       if (getcwd_fs (current_directory, GET_PATH_MAX) == 0)
  973. #else
  974.       if (getcwd (current_directory, GET_PATH_MAX) == 0)
  975. #endif
  976.     {
  977. #ifdef    HAVE_GETCWD
  978.       perror_with_name ("getcwd: ", "");
  979. #else
  980.       error ("getwd: %s", current_directory);
  981. #endif
  982.       starting_directory = 0;
  983.     }
  984.       else
  985.     starting_directory = current_directory;
  986.     }
  987.  
  988.   /* Read any stdin makefiles into temporary files.  */
  989.  
  990.   if (makefiles != 0)
  991.     {
  992.       register unsigned int i;
  993.       for (i = 0; i < makefiles->idx; ++i)
  994.     if (makefiles->list[i][0] == '-' && makefiles->list[i][1] == '\0')
  995.       {
  996.         /* This makefile is standard input.  Since we may re-exec
  997.            and thus re-read the makefiles, we read standard input
  998.            into a temporary file and read from that.  */
  999.         FILE *outfile;
  1000.  
  1001.         /* Make a unique filename.  */
  1002. #ifdef HAVE_MKTEMP
  1003.  
  1004. #ifdef VMS
  1005.         static char name[] = "sys$scratch:GmXXXXXX";
  1006. #else
  1007.         static char name[] = "/tmp/GmXXXXXX";
  1008. #endif
  1009.         (void) mktemp (name);
  1010. #else
  1011.         static char name[L_tmpnam];
  1012.         (void) tmpnam (name);
  1013. #endif
  1014.  
  1015.         outfile = fopen (name, "w");
  1016.         if (outfile == 0)
  1017.           pfatal_with_name ("fopen (temporary file)");
  1018.         while (!feof (stdin))
  1019.           {
  1020.         char buf[2048];
  1021.         unsigned int n = fread (buf, 1, sizeof(buf), stdin);
  1022.         if (n > 0 && fwrite (buf, 1, n, outfile) != n)
  1023.           pfatal_with_name ("fwrite (temporary file)");
  1024.           }
  1025.         /* Try to make sure we won't remake the temporary
  1026.            file when we are re-exec'd.  Kludge-o-matic!  */
  1027.         fprintf (outfile, "%s:;\n", name);
  1028.         (void) fclose (outfile);
  1029.  
  1030.         /* Replace the name that read_all_makefiles will
  1031.            see with the name of the temporary file.  */
  1032.         {
  1033.           char *temp;
  1034.           /* SGI compiler requires alloca's result be assigned simply.  */
  1035.           temp = (char *) alloca (sizeof (name));
  1036.           bcopy (name, temp, sizeof (name));
  1037.           makefiles->list[i] = temp;
  1038.         }
  1039.  
  1040.         /* Make sure the temporary file will not be remade.  */
  1041.         f = enter_file (savestring (name, sizeof name - 1));
  1042.         f->updated = 1;
  1043.         f->update_status = 0;
  1044.         f->command_state = cs_finished;
  1045.         /* Let it be removed when we're done.  */
  1046.         f->intermediate = 1;
  1047.         /* But don't mention it.  */
  1048.         f->dontcare = 1;
  1049.       }
  1050.     }
  1051.  
  1052.   /* Set up to handle children dying.  This must be done before
  1053.      reading in the makefiles so that `shell' function calls will work.  */
  1054.  
  1055. #ifdef SIGCHLD
  1056.   (void) signal (SIGCHLD, child_handler);
  1057. #endif
  1058. #ifdef SIGCLD
  1059.   (void) signal (SIGCLD, child_handler);
  1060. #endif
  1061.  
  1062.   /* Let the user send us SIGUSR1 to toggle the -d flag during the run.  */
  1063. #ifdef SIGUSR1
  1064.   (void) signal (SIGUSR1, debug_signal_handler);
  1065. #endif
  1066.  
  1067.   /* Define the initial list of suffixes for old-style rules.  */
  1068.  
  1069.   set_default_suffixes ();
  1070.  
  1071.   /* Define the file rules for the built-in suffix rules.  These will later
  1072.      be converted into pattern rules.  We used to do this in
  1073.      install_default_implicit_rules, but since that happens after reading
  1074.      makefiles, it results in the built-in pattern rules taking precedence
  1075.      over makefile-specified suffix rules, which is wrong.  */
  1076.  
  1077.   install_default_suffix_rules ();
  1078.  
  1079.   /* Define some internal and special variables.  */
  1080.  
  1081.   define_automatic_variables ();
  1082.  
  1083.   /* Set up the MAKEFLAGS and MFLAGS variables
  1084.      so makefiles can look at them.  */
  1085.  
  1086.   define_makeflags (0, 0);
  1087.  
  1088. #ifdef WINDOWS32
  1089.   /*
  1090.    * Now that makefiles are parsed, see if a Makefile gave a
  1091.    * value for SHELL and use that for default_shell instead if
  1092.    * that filename exists. This should speed up the
  1093.    * construct_argv_internal() function by avoiding unnecessary
  1094.    * recursion.
  1095.    */
  1096.   {
  1097.     struct variable *v = lookup_variable("SHELL", 5);
  1098.     extern char* default_shell;
  1099.  
  1100.     /*
  1101.      * to change value:
  1102.      *
  1103.      * SHELL must be found, SHELL must be set, value of SHELL
  1104.      * must be different from current value, and the
  1105.      * specified file must exist. Whew!
  1106.      */
  1107.     if (v != 0 && *v->value != '\0') {
  1108.       char *fn = recursively_expand(v);
  1109.  
  1110.       if (fn && strcmp(fn, default_shell) && file_exists_p(fn)) {
  1111.         char *p;
  1112.  
  1113.         default_shell = fn;
  1114.  
  1115.         /* if Makefile says SHELL is sh.exe, believe it */
  1116.         if (strstr(default_shell, "sh.exe"))
  1117.                no_default_sh_exe = 0;
  1118.  
  1119.         /*
  1120.          * Convert from backslashes to forward slashes so
  1121.          * create_command_line_argv_internal() is not confused.
  1122.          */
  1123.         for (p = strchr(default_shell, '\\'); p; p = strchr(default_shell, '\\'))
  1124.           *p = '/';
  1125.       }
  1126.     }
  1127.   }
  1128.   if (no_default_sh_exe && job_slots != 1) {
  1129.     error("Do not specify -j or --jobs if sh.exe is not available.");
  1130.     error("Resetting make for single job mode.");
  1131.     job_slots = 1;
  1132.   }
  1133. #endif /* WINDOWS32 */
  1134.  
  1135.   /* Define the default variables.  */
  1136.   define_default_variables ();
  1137.  
  1138.   /* Read all the makefiles.  */
  1139.  
  1140.   default_file = enter_file (".DEFAULT");
  1141.  
  1142.   read_makefiles
  1143.     = read_all_makefiles (makefiles == 0 ? (char **) 0 : makefiles->list);
  1144.  
  1145. #ifdef __MSDOS__
  1146.   /* We need to know what kind of shell we will be using.  */
  1147.   {
  1148.     extern int _is_unixy_shell (const char *_path);
  1149.     struct variable *shv = lookup_variable("SHELL", 5);
  1150.     extern int unixy_shell;
  1151.     extern char *default_shell;
  1152.  
  1153.     if (shv && *shv->value)
  1154.       {
  1155.     char *shell_path = recursively_expand(shv);
  1156.  
  1157.     if (shell_path && _is_unixy_shell (shell_path))
  1158.       unixy_shell = 1;
  1159.     else
  1160.       unixy_shell = 0;
  1161.     if (shell_path)
  1162.       default_shell = shell_path;
  1163.       }
  1164.   }
  1165. #endif /* __MSDOS__ */
  1166.  
  1167.   /* Decode switches again, in case the variables were set by the makefile.  */
  1168.   decode_env_switches ("MAKEFLAGS", 9);
  1169. #if 0
  1170.   decode_env_switches ("MFLAGS", 6);
  1171. #endif
  1172.  
  1173.   /* Set up MAKEFLAGS and MFLAGS again, so they will be right.  */
  1174.  
  1175.   define_makeflags (1, 0);
  1176.  
  1177.   /* Make each `struct dep' point at the `struct file' for the file
  1178.      depended on.  Also do magic for special targets.  */
  1179.  
  1180.   snap_deps ();
  1181.  
  1182.   /* Convert old-style suffix rules to pattern rules.  It is important to
  1183.      do this before installing the built-in pattern rules below, so that
  1184.      makefile-specified suffix rules take precedence over built-in pattern
  1185.      rules.  */
  1186.  
  1187.   convert_to_pattern ();
  1188.  
  1189.   /* Install the default implicit pattern rules.
  1190.      This used to be done before reading the makefiles.
  1191.      But in that case, built-in pattern rules were in the chain
  1192.      before user-defined ones, so they matched first.  */
  1193.  
  1194.   install_default_implicit_rules ();
  1195.  
  1196.   /* Compute implicit rule limits.  */
  1197.  
  1198.   count_implicit_rule_limits ();
  1199.  
  1200.   /* Construct the listings of directories in VPATH lists.  */
  1201.  
  1202.   build_vpath_lists ();
  1203.  
  1204.   /* Mark files given with -o flags as very old (00:00:01.00 Jan 1, 1970)
  1205.      and as having been updated already, and files given with -W flags as
  1206.      brand new (time-stamp as far as possible into the future).  */
  1207.  
  1208.   if (old_files != 0)
  1209.     for (p = old_files->list; *p != 0; ++p)
  1210.       {
  1211.     f = enter_command_line_file (*p);
  1212.     f->last_mtime = (time_t) 1;
  1213.     f->updated = 1;
  1214.     f->update_status = 0;
  1215.     f->command_state = cs_finished;
  1216.       }
  1217.  
  1218.   if (new_files != 0)
  1219.     {
  1220.       for (p = new_files->list; *p != 0; ++p)
  1221.     {
  1222.       f = enter_command_line_file (*p);
  1223.       f->last_mtime = NEW_MTIME;
  1224.     }
  1225.     }
  1226.  
  1227.   /* Initialize the remote job module.  */
  1228.   remote_setup ();
  1229.  
  1230.   if (read_makefiles != 0)
  1231.     {
  1232.       /* Update any makefiles if necessary.  */
  1233.  
  1234.       time_t *makefile_mtimes = 0;
  1235.       unsigned int mm_idx = 0;
  1236.       char **nargv = argv;
  1237.       int nargc = argc;
  1238.  
  1239.       if (debug_flag)
  1240.     puts ("Updating makefiles....");
  1241.  
  1242.       /* Remove any makefiles we don't want to try to update.
  1243.      Also record the current modtimes so we can compare them later.  */
  1244.       {
  1245.     register struct dep *d, *last;
  1246.     last = 0;
  1247.     d = read_makefiles;
  1248.     while (d != 0)
  1249.       {
  1250.         register struct file *f = d->file;
  1251.         if (f->double_colon)
  1252.           for (f = f->double_colon; f != NULL; f = f->prev)
  1253.         {
  1254.           if (f->deps == 0 && f->cmds != 0)
  1255.             {
  1256.               /* This makefile is a :: target with commands, but
  1257.              no dependencies.  So, it will always be remade.
  1258.              This might well cause an infinite loop, so don't
  1259.              try to remake it.  (This will only happen if
  1260.              your makefiles are written exceptionally
  1261.              stupidly; but if you work for Athena, that's how
  1262.              you write your makefiles.)  */
  1263.  
  1264.               if (debug_flag)
  1265.             printf ("Makefile `%s' might loop; not remaking it.\n",
  1266.                 f->name);
  1267.  
  1268.               if (last == 0)
  1269.             read_makefiles = d->next;
  1270.               else
  1271.             last->next = d->next;
  1272.  
  1273.               /* Free the storage.  */
  1274.               free ((char *) d);
  1275.  
  1276.               d = last == 0 ? 0 : last->next;
  1277.  
  1278.               break;
  1279.             }
  1280.         }
  1281.         if (f == NULL || !f->double_colon)
  1282.           {
  1283.         if (makefile_mtimes == 0)
  1284.           makefile_mtimes = (time_t *) xmalloc (sizeof (time_t));
  1285.         else
  1286.           makefile_mtimes = (time_t *)
  1287.             xrealloc ((char *) makefile_mtimes,
  1288.                   (mm_idx + 1) * sizeof (time_t));
  1289.         makefile_mtimes[mm_idx++] = file_mtime_no_search (d->file);
  1290.         last = d;
  1291.         d = d->next;
  1292.           }
  1293.       }
  1294.       }
  1295.  
  1296.       /* Set up `MAKEFLAGS' specially while remaking makefiles.  */
  1297.       define_makeflags (1, 1);
  1298.  
  1299.       switch (update_goal_chain (read_makefiles, 1))
  1300.     {
  1301.     case 1:
  1302.     default:
  1303. #define BOGUS_UPDATE_STATUS 0
  1304.       assert (BOGUS_UPDATE_STATUS);
  1305.       break;
  1306.  
  1307.     case -1:
  1308.       /* Did nothing.  */
  1309.       break;
  1310.  
  1311.     case 2:
  1312.       /* Failed to update.  Figure out if we care.  */
  1313.       {
  1314.         /* Nonzero if any makefile was successfully remade.  */
  1315.         int any_remade = 0;
  1316.         /* Nonzero if any makefile we care about failed
  1317.            in updating or could not be found at all.  */
  1318.         int any_failed = 0;
  1319.         register unsigned int i;
  1320.             struct dep *d;
  1321.  
  1322.         for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
  1323.               if (d->file->updated)
  1324.                 {
  1325.                   /* This makefile was updated.  */
  1326.                   if (d->file->update_status == 0)
  1327.                     {
  1328.                       /* It was successfully updated.  */
  1329.                       any_remade |= (file_mtime_no_search (d->file)
  1330.                                      != makefile_mtimes[i]);
  1331.                     }
  1332.                   else if (! (d->changed & RM_DONTCARE))
  1333.                     {
  1334.                       time_t mtime;
  1335.                       /* The update failed and this makefile was not
  1336.                          from the MAKEFILES variable, so we care.  */
  1337.                       error ("Failed to remake makefile `%s'.",
  1338.                              d->file->name);
  1339.                       mtime = file_mtime_no_search (d->file);
  1340.                       any_remade |= (mtime != (time_t) -1
  1341.                                      && mtime != makefile_mtimes[i]);
  1342.                     }
  1343.                 }
  1344.               else
  1345.                 /* This makefile was not found at all.  */
  1346.                 if (! (d->changed & RM_DONTCARE))
  1347.                   {
  1348.                     /* This is a makefile we care about.  See how much.  */
  1349.                     if (d->changed & RM_INCLUDED)
  1350.                       /* An included makefile.  We don't need
  1351.                          to die, but we do want to complain.  */
  1352.                       error ("Included makefile `%s' was not found.",
  1353.                              dep_name (d));
  1354.                     else
  1355.                       {
  1356.                         /* A normal makefile.  We must die later.  */
  1357.                         error ("Makefile `%s' was not found", dep_name (d));
  1358.                         any_failed = 1;
  1359.                       }
  1360.                   }
  1361.  
  1362.         if (any_remade)
  1363.           goto re_exec;
  1364.         else if (any_failed)
  1365.           die (2);
  1366.         else
  1367.           break;
  1368.       }
  1369.  
  1370.     case 0:
  1371.     re_exec:
  1372.       /* Updated successfully.  Re-exec ourselves.  */
  1373.  
  1374.       remove_intermediates (0);
  1375.  
  1376.       if (print_data_base_flag)
  1377.         print_data_base ();
  1378.  
  1379.       log_working_directory (0);
  1380.  
  1381.       if (makefiles != 0)
  1382.         {
  1383.           /* These names might have changed.  */
  1384.           register unsigned int i, j = 0;
  1385.           for (i = 1; i < argc; ++i)
  1386.         if (!strncmp (argv[i], "-f", 2)) /* XXX */
  1387.           {
  1388.             char *p = &argv[i][2];
  1389.             if (*p == '\0')
  1390.               argv[++i] = makefiles->list[j];
  1391.             else
  1392.               argv[i] = concat ("-f", makefiles->list[j], "");
  1393.             ++j;
  1394.           }
  1395.         }
  1396.  
  1397.           /* Add -o options for all makefiles that were remade */
  1398.           {
  1399.             register unsigned int i;
  1400.             struct dep *d;
  1401.  
  1402.             for (i = argc+1, d = read_makefiles; d != 0; d = d->next)
  1403.               i += d->file->updated != 0;
  1404.  
  1405.             nargv = (char **)xmalloc(i * sizeof(char *));
  1406.             bcopy(argv, nargv, argc * sizeof(char *));
  1407.  
  1408.             for (i = 0, d = read_makefiles; d != 0; ++i, d = d->next)
  1409.               {
  1410.                 if (d->file->updated)
  1411.                   nargv[nargc++] = concat("-o", dep_name(d), "");
  1412.               }
  1413.             nargv[nargc] = 0;
  1414.           }
  1415.  
  1416.       if (directories != 0 && directories->idx > 0)
  1417.         {
  1418.           char bad;
  1419.           if (directory_before_chdir != 0)
  1420.         {
  1421.           if (chdir (directory_before_chdir) < 0)
  1422.             {
  1423.               perror_with_name ("chdir", "");
  1424.               bad = 1;
  1425.             }
  1426.           else
  1427.             bad = 0;
  1428.         }
  1429.           else
  1430.         bad = 1;
  1431.           if (bad)
  1432.         fatal ("Couldn't change back to original directory.");
  1433.         }
  1434.  
  1435. #ifndef _AMIGA
  1436.       for (p = environ; *p != 0; ++p)
  1437.         if (!strncmp (*p, "MAKELEVEL=", 10))
  1438.           {
  1439.         /* The SGI compiler apparently can't understand
  1440.            the concept of storing the result of a function
  1441.            in something other than a local variable.  */
  1442.         char *sgi_loses;
  1443.         sgi_loses = (char *) alloca (40);
  1444.         *p = sgi_loses;
  1445.         sprintf (*p, "MAKELEVEL=%u", makelevel);
  1446.         break;
  1447.           }
  1448. #else /* AMIGA */
  1449.       {
  1450.         amiga_set_makelevel(makelevel);
  1451.       }
  1452. #endif
  1453.  
  1454.       if (debug_flag)
  1455.         {
  1456.           char **p;
  1457.           fputs ("Re-executing:", stdout);
  1458.           for (p = nargv; *p != 0; ++p)
  1459.         printf (" %s", *p);
  1460.           puts ("");
  1461.         }
  1462.  
  1463.       fflush (stdout);
  1464.       fflush (stderr);
  1465.  
  1466. #ifndef _AMIGA
  1467.       exec_command (nargv, environ);
  1468. #else
  1469.       exec_command (nargv);
  1470.       exit (0);
  1471. #endif
  1472.       /* NOTREACHED */
  1473.     }
  1474.     }
  1475.  
  1476.   /* Set up `MAKEFLAGS' again for the normal targets.  */
  1477.   define_makeflags (1, 0);
  1478.  
  1479.   {
  1480.     int status;
  1481.  
  1482.     /* If there were no command-line goals, use the default.  */
  1483.     if (goals == 0)
  1484.       {
  1485.     if (default_goal_file != 0)
  1486.       {
  1487.         goals = (struct dep *) xmalloc (sizeof (struct dep));
  1488.         goals->next = 0;
  1489.         goals->name = 0;
  1490.         goals->file = default_goal_file;
  1491.       }
  1492.       }
  1493.     else
  1494.       lastgoal->next = 0;
  1495.  
  1496.     if (goals != 0)
  1497.       {
  1498.     /* Update the goals.  */
  1499.  
  1500.     if (debug_flag)
  1501.       puts ("Updating goal targets....");
  1502.  
  1503.     switch (update_goal_chain (goals, 0))
  1504.       {
  1505.       case -1:
  1506.         /* Nothing happened.  */
  1507.       case 0:
  1508.         /* Updated successfully.  */
  1509.         status = EXIT_SUCCESS;
  1510.         break;
  1511.       case 2:
  1512.         /* Updating failed.  POSIX.2 specifies exit status >1 for this;
  1513.            but in VMS, there is only success and failure.  */
  1514.         status = EXIT_FAILURE ? 2 : EXIT_FAILURE;
  1515.         break;
  1516.       case 1:
  1517.         /* We are under -q and would run some commands.  */
  1518.         status = EXIT_FAILURE;
  1519.         break;
  1520.       default:
  1521.         abort ();
  1522.       }
  1523.       }
  1524.     else
  1525.       {
  1526.     if (read_makefiles == 0)
  1527.       fatal ("No targets specified and no makefile found");
  1528.     else
  1529.       fatal ("No targets");
  1530.       }
  1531.  
  1532.     /* If we detected some clock skew, generate one last warning */
  1533.     if (clock_skew_detected)
  1534.       error("*** Warning:  Clock skew detected.  Your build may be incomplete.");
  1535.  
  1536.     /* Exit.  */
  1537.     die (status);
  1538.   }
  1539.  
  1540.   return 0;
  1541. }
  1542.  
  1543. /* Parsing of arguments, decoding of switches.  */
  1544.  
  1545. static char options[1 + sizeof (switches) / sizeof (switches[0]) * 3];
  1546. static struct option long_options[(sizeof (switches) / sizeof (switches[0])) +
  1547.                   (sizeof (long_option_aliases) /
  1548.                    sizeof (long_option_aliases[0]))];
  1549.  
  1550. /* Fill in the string and vector for getopt.  */
  1551. static void
  1552. init_switches ()
  1553. {
  1554.   register char *p;
  1555.   register int c;
  1556.   register unsigned int i;
  1557.  
  1558.   if (options[0] != '\0')
  1559.     /* Already done.  */
  1560.     return;
  1561.  
  1562.   p = options;
  1563.  
  1564.   /* Return switch and non-switch args in order, regardless of
  1565.      POSIXLY_CORRECT.  Non-switch args are returned as option 1.  */
  1566.   *p++ = '-';
  1567.  
  1568.   for (i = 0; switches[i].c != '\0'; ++i)
  1569.     {
  1570.       long_options[i].name = (switches[i].long_name == 0 ? "" :
  1571.                   switches[i].long_name);
  1572.       long_options[i].flag = 0;
  1573.       long_options[i].val = switches[i].c;
  1574.       if (isalnum (switches[i].c))
  1575.     *p++ = switches[i].c;
  1576.       switch (switches[i].type)
  1577.     {
  1578.     case flag:
  1579.     case flag_off:
  1580.     case ignore:
  1581.       long_options[i].has_arg = no_argument;
  1582.       break;
  1583.  
  1584.     case string:
  1585.     case positive_int:
  1586.     case floating:
  1587.       if (isalnum (switches[i].c))
  1588.         *p++ = ':';
  1589.       if (switches[i].noarg_value != 0)
  1590.         {
  1591.           if (isalnum (switches[i].c))
  1592.         *p++ = ':';
  1593.           long_options[i].has_arg = optional_argument;
  1594.         }
  1595.       else
  1596.         long_options[i].has_arg = required_argument;
  1597.       break;
  1598.     }
  1599.     }
  1600.   *p = '\0';
  1601.   for (c = 0; c < (sizeof (long_option_aliases) /
  1602.            sizeof (long_option_aliases[0]));
  1603.        ++c)
  1604.     long_options[i++] = long_option_aliases[c];
  1605.   long_options[i].name = 0;
  1606. }
  1607.  
  1608. static void
  1609. handle_non_switch_argument (arg, env)
  1610.      char *arg;
  1611.      int env;
  1612. {
  1613.   /* Non-option argument.  It might be a variable definition.  */
  1614.   struct variable *v;
  1615.   if (arg[0] == '-' && arg[1] == '\0')
  1616.     /* Ignore plain `-' for compatibility.  */
  1617.     return;
  1618.   v = try_variable_definition ((char *) 0, 0, arg, o_command);
  1619.   if (v != 0)
  1620.     {
  1621.       /* It is indeed a variable definition.  Record a pointer to
  1622.      the variable for later use in define_makeflags.  */
  1623.       struct command_variable *cv
  1624.     = (struct command_variable *) xmalloc (sizeof (*cv));
  1625.       cv->variable = v;
  1626.       cv->next = command_variables;
  1627.       command_variables = cv;
  1628.     }
  1629.   else if (! env)
  1630.     {
  1631.       /* Not an option or variable definition; it must be a goal
  1632.      target!  Enter it as a file and add it to the dep chain of
  1633.      goals.  */
  1634.       struct file *f = enter_command_line_file (arg);
  1635.       f->cmd_target = 1;
  1636.  
  1637.       if (goals == 0)
  1638.     {
  1639.       goals = (struct dep *) xmalloc (sizeof (struct dep));
  1640.       lastgoal = goals;
  1641.     }
  1642.       else
  1643.     {
  1644.       lastgoal->next
  1645.         = (struct dep *) xmalloc (sizeof (struct dep));
  1646.       lastgoal = lastgoal->next;
  1647.     }
  1648.       lastgoal->name = 0;
  1649.       lastgoal->file = f;
  1650.  
  1651.       {
  1652.         /* Add this target name to the MAKECMDGOALS variable. */
  1653.         struct variable *v;
  1654.         char *value;
  1655.  
  1656.         v = lookup_variable("MAKECMDGOALS", 12);
  1657.         if (v == 0)
  1658.           value = f->name;
  1659.         else
  1660.           {
  1661.             /* Paste the old and new values together */
  1662.             unsigned int oldlen, newlen;
  1663.  
  1664.             oldlen = strlen(v->value);
  1665.             newlen = strlen(f->name);
  1666.             value = (char *)alloca(oldlen + 1 + newlen + 1);
  1667.             bcopy(v->value, value, oldlen);
  1668.             value[oldlen] = ' ';
  1669.             bcopy(f->name, &value[oldlen + 1], newlen + 1);
  1670.           }
  1671.         define_variable("MAKECMDGOALS", 12, value, o_default, 0);
  1672.       }
  1673.     }
  1674. }
  1675.  
  1676. /* Decode switches from ARGC and ARGV.
  1677.    They came from the environment if ENV is nonzero.  */
  1678.  
  1679. static void
  1680. decode_switches (argc, argv, env)
  1681.      int argc;
  1682.      char **argv;
  1683.      int env;
  1684. {
  1685.   int bad = 0;
  1686.   register const struct command_switch *cs;
  1687.   register struct stringlist *sl;
  1688.   register int c;
  1689.  
  1690.   /* getopt does most of the parsing for us.
  1691.      First, get its vectors set up.  */
  1692.  
  1693.   init_switches ();
  1694.  
  1695.   /* Let getopt produce error messages for the command line,
  1696.      but not for options from the environment.  */
  1697.   opterr = !env;
  1698.   /* Reset getopt's state.  */
  1699.   optind = 0;
  1700.  
  1701.   while (optind < argc)
  1702.     {
  1703.       /* Parse the next argument.  */
  1704.       c = getopt_long (argc, argv, options, long_options, (int *) 0);
  1705.       if (c == EOF)
  1706.     /* End of arguments, or "--" marker seen.  */
  1707.     break;
  1708.       else if (c == 1)
  1709.     /* An argument not starting with a dash.  */
  1710.     handle_non_switch_argument (optarg, env);
  1711.       else if (c == '?')
  1712.     /* Bad option.  We will print a usage message and die later.
  1713.        But continue to parse the other options so the user can
  1714.        see all he did wrong.  */
  1715.     bad = 1;
  1716.       else
  1717.     for (cs = switches; cs->c != '\0'; ++cs)
  1718.       if (cs->c == c)
  1719.         {
  1720.           /* Whether or not we will actually do anything with
  1721.          this switch.  We test this individually inside the
  1722.          switch below rather than just once outside it, so that
  1723.          options which are to be ignored still consume args.  */
  1724.           int doit = !env || cs->env;
  1725.  
  1726.           switch (cs->type)
  1727.         {
  1728.         default:
  1729.           abort ();
  1730.  
  1731.         case ignore:
  1732.           break;
  1733.  
  1734.         case flag:
  1735.         case flag_off:
  1736.           if (doit)
  1737.             *(int *) cs->value_ptr = cs->type == flag;
  1738.           break;
  1739.  
  1740.         case string:
  1741.           if (!doit)
  1742.             break;
  1743.  
  1744.           if (optarg == 0)
  1745.             optarg = cs->noarg_value;
  1746.  
  1747.           sl = *(struct stringlist **) cs->value_ptr;
  1748.           if (sl == 0)
  1749.             {
  1750.               sl = (struct stringlist *)
  1751.             xmalloc (sizeof (struct stringlist));
  1752.               sl->max = 5;
  1753.               sl->idx = 0;
  1754.               sl->list = (char **) xmalloc (5 * sizeof (char *));
  1755.               *(struct stringlist **) cs->value_ptr = sl;
  1756.             }
  1757.           else if (sl->idx == sl->max - 1)
  1758.             {
  1759.               sl->max += 5;
  1760.               sl->list = (char **)
  1761.             xrealloc ((char *) sl->list,
  1762.                   sl->max * sizeof (char *));
  1763.             }
  1764.           sl->list[sl->idx++] = optarg;
  1765.           sl->list[sl->idx] = 0;
  1766.           break;
  1767.  
  1768.         case positive_int:
  1769.           if (optarg == 0 && argc > optind
  1770.               && isdigit (argv[optind][0]))
  1771.             optarg = argv[optind++];
  1772.  
  1773.           if (!doit)
  1774.             break;
  1775.  
  1776.           if (optarg != 0)
  1777.             {
  1778.               int i = atoi (optarg);
  1779.               if (i < 1)
  1780.             {
  1781.               if (doit)
  1782.                 error ("the `-%c' option requires a \
  1783. positive integral argument",
  1784.                    cs->c);
  1785.               bad = 1;
  1786.             }
  1787.               else
  1788.             *(unsigned int *) cs->value_ptr = i;
  1789.             }
  1790.           else
  1791.             *(unsigned int *) cs->value_ptr
  1792.               = *(unsigned int *) cs->noarg_value;
  1793.           break;
  1794.  
  1795. #ifndef NO_FLOAT
  1796.         case floating:
  1797.           if (optarg == 0 && optind < argc
  1798.               && (isdigit (argv[optind][0]) || argv[optind][0] == '.'))
  1799.             optarg = argv[optind++];
  1800.  
  1801.           if (doit)
  1802.             *(double *) cs->value_ptr
  1803.               = (optarg != 0 ? atof (optarg)
  1804.              : *(double *) cs->noarg_value);
  1805.  
  1806.           break;
  1807. #endif
  1808.         }
  1809.  
  1810.           /* We've found the switch.  Stop looking.  */
  1811.           break;
  1812.         }
  1813.     }
  1814.  
  1815.   /* There are no more options according to getting getopt, but there may
  1816.      be some arguments left.  Since we have asked for non-option arguments
  1817.      to be returned in order, this only happens when there is a "--"
  1818.      argument to prevent later arguments from being options.  */
  1819.   while (optind < argc)
  1820.     handle_non_switch_argument (argv[optind++], env);
  1821.  
  1822.  
  1823.   if (!env && (bad || print_usage_flag))
  1824.     {
  1825.       /* Print a nice usage message.  */
  1826.       FILE *usageto;
  1827.  
  1828.       if (print_version_flag)
  1829.     print_version ();
  1830.  
  1831.       usageto = bad ? stderr : stdout;
  1832.  
  1833.       fprintf (usageto, "Usage: %s [options] [target] ...\n", program);
  1834.  
  1835.       fputs ("Options:\n", usageto);
  1836.       for (cs = switches; cs->c != '\0'; ++cs)
  1837.     {
  1838.       char buf[1024], shortarg[50], longarg[50], *p;
  1839.  
  1840.       if (cs->description[0] == '-')
  1841.         continue;
  1842.  
  1843.       switch (long_options[cs - switches].has_arg)
  1844.         {
  1845.         case no_argument:
  1846.           shortarg[0] = longarg[0] = '\0';
  1847.           break;
  1848.         case required_argument:
  1849.           sprintf (longarg, "=%s", cs->argdesc);
  1850.           sprintf (shortarg, " %s", cs->argdesc);
  1851.           break;
  1852.         case optional_argument:
  1853.           sprintf (longarg, "[=%s]", cs->argdesc);
  1854.           sprintf (shortarg, " [%s]", cs->argdesc);
  1855.           break;
  1856.         }
  1857.  
  1858.       p = buf;
  1859.  
  1860.       if (isalnum (cs->c))
  1861.         {
  1862.           sprintf (buf, "  -%c%s", cs->c, shortarg);
  1863.           p += strlen (p);
  1864.         }
  1865.       if (cs->long_name != 0)
  1866.         {
  1867.           unsigned int i;
  1868.           sprintf (p, "%s--%s%s",
  1869.                !isalnum (cs->c) ? "  " : ", ",
  1870.                cs->long_name, longarg);
  1871.           p += strlen (p);
  1872.           for (i = 0; i < (sizeof (long_option_aliases) /
  1873.                    sizeof (long_option_aliases[0]));
  1874.            ++i)
  1875.         if (long_option_aliases[i].val == cs->c)
  1876.           {
  1877.             sprintf (p, ", --%s%s",
  1878.                  long_option_aliases[i].name, longarg);
  1879.             p += strlen (p);
  1880.           }
  1881.         }
  1882.       {
  1883.         const struct command_switch *ncs = cs;
  1884.         while ((++ncs)->c != '\0')
  1885.           if (ncs->description[0] == '-' &&
  1886.           ncs->description[1] == cs->c)
  1887.         {
  1888.           /* This is another switch that does the same
  1889.              one as the one we are processing.  We want
  1890.              to list them all together on one line.  */
  1891.           sprintf (p, ", -%c%s", ncs->c, shortarg);
  1892.           p += strlen (p);
  1893.           if (ncs->long_name != 0)
  1894.             {
  1895.               sprintf (p, ", --%s%s", ncs->long_name, longarg);
  1896.               p += strlen (p);
  1897.             }
  1898.         }
  1899.       }
  1900.  
  1901.       if (p - buf > DESCRIPTION_COLUMN - 2)
  1902.         /* The list of option names is too long to fit on the same
  1903.            line with the description, leaving at least two spaces.
  1904.            Print it on its own line instead.  */
  1905.         {
  1906.           fprintf (usageto, "%s\n", buf);
  1907.           buf[0] = '\0';
  1908.         }
  1909.  
  1910.       fprintf (usageto, "%*s%s.\n",
  1911.            - DESCRIPTION_COLUMN,
  1912.            buf, cs->description);
  1913.     }
  1914.  
  1915.       die (bad ? 2 : 0);
  1916.     }
  1917. }
  1918.  
  1919. /* Decode switches from environment variable ENVAR (which is LEN chars long).
  1920.    We do this by chopping the value into a vector of words, prepending a
  1921.    dash to the first word if it lacks one, and passing the vector to
  1922.    decode_switches.  */
  1923.  
  1924. static void
  1925. decode_env_switches (envar, len)
  1926.      char *envar;
  1927.      unsigned int len;
  1928. {
  1929.   char *varref = (char *) alloca (2 + len + 2);
  1930.   char *value, *p;
  1931.   int argc;
  1932.   char **argv;
  1933.  
  1934.   /* Get the variable's value.  */
  1935.   varref[0] = '$';
  1936.   varref[1] = '(';
  1937.   bcopy (envar, &varref[2], len);
  1938.   varref[2 + len] = ')';
  1939.   varref[2 + len + 1] = '\0';
  1940.   value = variable_expand (varref);
  1941.  
  1942.   /* Skip whitespace, and check for an empty value.  */
  1943.   value = next_token (value);
  1944.   len = strlen (value);
  1945.   if (len == 0)
  1946.     return;
  1947.  
  1948.   /* Allocate a vector that is definitely big enough.  */
  1949.   argv = (char **) alloca ((1 + len + 1) * sizeof (char *));
  1950.  
  1951.   /* Allocate a buffer to copy the value into while we split it into words
  1952.      and unquote it.  We must use permanent storage for this because
  1953.      decode_switches may store pointers into the passed argument words.  */
  1954.   p = (char *) xmalloc (2 * len);
  1955.  
  1956.   /* getopt will look at the arguments starting at ARGV[1].
  1957.      Prepend a spacer word.  */
  1958.   argv[0] = 0;
  1959.   argc = 1;
  1960.   argv[argc] = p;
  1961.   while (*value != '\0')
  1962.     {
  1963.       if (*value == '\\')
  1964.     ++value;        /* Skip the backslash.  */
  1965.       else if (isblank (*value))
  1966.     {
  1967.       /* End of the word.  */
  1968.       *p++ = '\0';
  1969.       argv[++argc] = p;
  1970.       do
  1971.         ++value;
  1972.       while (isblank (*value));
  1973.       continue;
  1974.     }
  1975.       *p++ = *value++;
  1976.     }
  1977.   *p = '\0';
  1978.   argv[++argc] = 0;
  1979.  
  1980.   if (argv[1][0] != '-' && index (argv[1], '=') == 0)
  1981.     /* The first word doesn't start with a dash and isn't a variable
  1982.        definition.  Add a dash and pass it along to decode_switches.  We
  1983.        need permanent storage for this in case decode_switches saves
  1984.        pointers into the value.  */
  1985.     argv[1] = concat ("-", argv[1], "");
  1986.  
  1987.   /* Parse those words.  */
  1988.   decode_switches (argc, argv, 1);
  1989. }
  1990.  
  1991. /* Quote the string IN so that it will be interpreted as a single word with
  1992.    no magic by the shell; if DOUBLE_DOLLARS is nonzero, also double dollar
  1993.    signs to avoid variable expansion in make itself.  Write the result into
  1994.    OUT, returning the address of the next character to be written.
  1995.    Allocating space for OUT twice the length of IN (thrice if
  1996.    DOUBLE_DOLLARS is nonzero) is always sufficient.  */
  1997.  
  1998. static char *
  1999. quote_as_word (out, in, double_dollars)
  2000.      char *out, *in;
  2001.      int double_dollars;
  2002. {
  2003.   while (*in != '\0')
  2004.     {
  2005. #ifdef VMS
  2006.       if (index ("^;'\"*?$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
  2007. #else
  2008.       if (index ("^;'\"*?[]$<>(){}|&~`\\ \t\r\n\f\v", *in) != 0)
  2009. #endif
  2010.     *out++ = '\\';
  2011.       if (double_dollars && *in == '$')
  2012.     *out++ = '$';
  2013.       *out++ = *in++;
  2014.     }
  2015.  
  2016.   return out;
  2017. }
  2018.  
  2019. /* Define the MAKEFLAGS and MFLAGS variables to reflect the settings of the
  2020.    command switches.  Include options with args if ALL is nonzero.
  2021.    Don't include options with the `no_makefile' flag set if MAKEFILE.  */
  2022.  
  2023. static void
  2024. define_makeflags (all, makefile)
  2025.      int all, makefile;
  2026. {
  2027.   static const char ref[] = "$(MAKEOVERRIDES)";
  2028.   static const char posixref[] = "$(-*-command-variables-*-)";
  2029.   register const struct command_switch *cs;
  2030.   char *flagstring;
  2031.   register char *p;
  2032.   unsigned int words;
  2033.   struct variable *v;
  2034.  
  2035.   /* We will construct a linked list of `struct flag's describing
  2036.      all the flags which need to go in MAKEFLAGS.  Then, once we
  2037.      know how many there are and their lengths, we can put them all
  2038.      together in a string.  */
  2039.  
  2040.   struct flag
  2041.     {
  2042.       struct flag *next;
  2043.       const struct command_switch *cs;
  2044.       char *arg;
  2045.     };
  2046.   struct flag *flags = 0;
  2047.   unsigned int flagslen = 0;
  2048. #define    ADD_FLAG(ARG, LEN) \
  2049.   do {                                          \
  2050.     struct flag *new = (struct flag *) alloca (sizeof (struct flag));          \
  2051.     new->cs = cs;                                  \
  2052.     new->arg = (ARG);                                  \
  2053.     new->next = flags;                                  \
  2054.     flags = new;                                  \
  2055.     if (new->arg == 0)                                  \
  2056.       ++flagslen;        /* Just a single flag letter.  */          \
  2057.     else                                      \
  2058.       flagslen += 1 + 1 + 1 + 1 + 3 * (LEN); /* " -x foo" */              \
  2059.     if (!isalnum (cs->c))                              \
  2060.       /* This switch has no single-letter version, so we use the long.  */    \
  2061.       flagslen += 2 + strlen (cs->long_name);                      \
  2062.   } while (0)
  2063.  
  2064.   for (cs = switches; cs->c != '\0'; ++cs)
  2065.     if (cs->toenv && (!makefile || !cs->no_makefile))
  2066.       switch (cs->type)
  2067.     {
  2068.     default:
  2069.       abort ();
  2070.  
  2071.     case ignore:
  2072.       break;
  2073.  
  2074.     case flag:
  2075.     case flag_off:
  2076.       if (!*(int *) cs->value_ptr == (cs->type == flag_off)
  2077.           && (cs->default_value == 0
  2078.           || *(int *) cs->value_ptr != *(int *) cs->default_value))
  2079.         ADD_FLAG (0, 0);
  2080.       break;
  2081.  
  2082.     case positive_int:
  2083.       if (all)
  2084.         {
  2085.           if ((cs->default_value != 0
  2086.            && (*(unsigned int *) cs->value_ptr
  2087.                == *(unsigned int *) cs->default_value)))
  2088.         break;
  2089.           else if (cs->noarg_value != 0
  2090.                && (*(unsigned int *) cs->value_ptr ==
  2091.                *(unsigned int *) cs->noarg_value))
  2092.         ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
  2093.           else if (cs->c == 'j')
  2094.         /* Special case for `-j'.  */
  2095.         ADD_FLAG ("1", 1);
  2096.           else
  2097.         {
  2098.           char *buf = (char *) alloca (30);
  2099.           sprintf (buf, "%u", *(unsigned int *) cs->value_ptr);
  2100.           ADD_FLAG (buf, strlen (buf));
  2101.         }
  2102.         }
  2103.       break;
  2104.  
  2105. #ifndef NO_FLOAT
  2106.     case floating:
  2107.       if (all)
  2108.         {
  2109.           if (cs->default_value != 0
  2110.           && (*(double *) cs->value_ptr
  2111.               == *(double *) cs->default_value))
  2112.         break;
  2113.           else if (cs->noarg_value != 0
  2114.                && (*(double *) cs->value_ptr
  2115.                == *(double *) cs->noarg_value))
  2116.         ADD_FLAG ("", 0); /* Optional value omitted; see below.  */
  2117.           else
  2118.         {
  2119.           char *buf = (char *) alloca (100);
  2120.           sprintf (buf, "%g", *(double *) cs->value_ptr);
  2121.           ADD_FLAG (buf, strlen (buf));
  2122.         }
  2123.         }
  2124.       break;
  2125. #endif
  2126.  
  2127.     case string:
  2128.       if (all)
  2129.         {
  2130.           struct stringlist *sl = *(struct stringlist **) cs->value_ptr;
  2131.           if (sl != 0)
  2132.         {
  2133.           /* Add the elements in reverse order, because
  2134.              all the flags get reversed below; and the order
  2135.              matters for some switches (like -I).  */
  2136.           register unsigned int i = sl->idx;
  2137.           while (i-- > 0)
  2138.             ADD_FLAG (sl->list[i], strlen (sl->list[i]));
  2139.         }
  2140.         }
  2141.       break;
  2142.     }
  2143.  
  2144.   flagslen += 4 + sizeof posixref; /* Four more for the possible " -- ".  */
  2145.  
  2146. #undef    ADD_FLAG
  2147.  
  2148.   /* Construct the value in FLAGSTRING.
  2149.      We allocate enough space for a preceding dash and trailing null.  */
  2150.   flagstring = (char *) alloca (1 + flagslen + 1);
  2151.   p = flagstring;
  2152.   words = 1;
  2153.   *p++ = '-';
  2154.   while (flags != 0)
  2155.     {
  2156.       /* Add the flag letter or name to the string.  */
  2157.       if (!isalnum (flags->cs->c))
  2158.     {
  2159.       *p++ = '-';
  2160.       strcpy (p, flags->cs->long_name);
  2161.       p += strlen (p);
  2162.     }
  2163.       else
  2164.     *p++ = flags->cs->c;
  2165.       if (flags->arg != 0)
  2166.     {
  2167.       /* A flag that takes an optional argument which in this case is
  2168.          omitted is specified by ARG being "".  We must distinguish
  2169.          because a following flag appended without an intervening " -"
  2170.          is considered the arg for the first.  */
  2171.       if (flags->arg[0] != '\0')
  2172.         {
  2173.           /* Add its argument too.  */
  2174.           *p++ = !isalnum (flags->cs->c) ? '=' : ' ';
  2175.           p = quote_as_word (p, flags->arg, 1);
  2176.         }
  2177.       ++words;
  2178.       /* Write a following space and dash, for the next flag.  */
  2179.       *p++ = ' ';
  2180.       *p++ = '-';
  2181.     }
  2182.       else if (!isalnum (flags->cs->c))
  2183.     {
  2184.       ++words;
  2185.       /* Long options must each go in their own word,
  2186.          so we write the following space and dash.  */
  2187.       *p++ = ' ';
  2188.       *p++ = '-';
  2189.     }
  2190.       flags = flags->next;
  2191.     }
  2192.  
  2193.   /* Define MFLAGS before appending variable definitions.  */
  2194.  
  2195.   if (p == &flagstring[1])
  2196.     /* No flags.  */
  2197.     flagstring[0] = '\0';
  2198.   else if (p[-1] == '-')
  2199.     {
  2200.       /* Kill the final space and dash.  */
  2201.       p -= 2;
  2202.       *p = '\0';
  2203.     }
  2204.   else
  2205.     /* Terminate the string.  */
  2206.     *p = '\0';
  2207.  
  2208.   /* Since MFLAGS is not parsed for flags, there is no reason to
  2209.      override any makefile redefinition.  */
  2210.   (void) define_variable ("MFLAGS", 6, flagstring, o_env, 1);
  2211.  
  2212.   if (all && command_variables != 0)
  2213.     {
  2214.       /* Now write a reference to $(MAKEOVERRIDES), which contains all the
  2215.      command-line variable definitions.  */
  2216.  
  2217.       if (p == &flagstring[1])
  2218.     /* No flags written, so elide the leading dash already written.  */
  2219.     p = flagstring;
  2220.       else
  2221.     {
  2222.       /* Separate the variables from the switches with a "--" arg.  */
  2223.       if (p[-1] != '-')
  2224.         {
  2225.           /* We did not already write a trailing " -".  */
  2226.           *p++ = ' ';
  2227.           *p++ = '-';
  2228.         }
  2229.       /* There is a trailing " -"; fill it out to " -- ".  */
  2230.       *p++ = '-';
  2231.       *p++ = ' ';
  2232.     }
  2233.  
  2234.       /* Copy in the string.  */
  2235.       if (posix_pedantic)
  2236.     {
  2237.       bcopy (posixref, p, sizeof posixref - 1);
  2238.       p += sizeof posixref - 1;
  2239.     }
  2240.       else
  2241.     {
  2242.       bcopy (ref, p, sizeof ref - 1);
  2243.       p += sizeof ref - 1;
  2244.     }
  2245.     }
  2246.   else if (p == &flagstring[1])
  2247.     {
  2248.       words = 0;
  2249.       --p;
  2250.     }
  2251.   else if (p[-1] == '-')
  2252.     /* Kill the final space and dash.  */
  2253.     p -= 2;
  2254.   /* Terminate the string.  */
  2255.   *p = '\0';
  2256.  
  2257.   v = define_variable ("MAKEFLAGS", 9,
  2258.                /* If there are switches, omit the leading dash
  2259.               unless it is a single long option with two
  2260.               leading dashes.  */
  2261.                &flagstring[(flagstring[0] == '-'
  2262.                     && flagstring[1] != '-')
  2263.                    ? 1 : 0],
  2264.                /* This used to use o_env, but that lost when a
  2265.               makefile defined MAKEFLAGS.  Makefiles set
  2266.               MAKEFLAGS to add switches, but we still want
  2267.               to redefine its value with the full set of
  2268.               switches.  Of course, an override or command
  2269.               definition will still take precedence.  */
  2270.                o_file, 1);
  2271.   if (! all)
  2272.     /* The first time we are called, set MAKEFLAGS to always be exported.
  2273.        We should not do this again on the second call, because that is
  2274.        after reading makefiles which might have done `unexport MAKEFLAGS'. */
  2275.     v->export = v_export;
  2276. }
  2277.  
  2278. /* Print version information.  */
  2279.  
  2280. static void
  2281. print_version ()
  2282. {
  2283.   static int printed_version = 0;
  2284.  
  2285.   char *precede = print_data_base_flag ? "# " : "";
  2286.  
  2287.   if (printed_version)
  2288.     /* Do it only once.  */
  2289.     return;
  2290.  
  2291.   printf ("%sGNU Make version %s", precede, version_string);
  2292.   if (remote_description != 0 && *remote_description != '\0')
  2293.     printf ("-%s", remote_description);
  2294.  
  2295.   printf (", by Richard Stallman and Roland McGrath.\n\
  2296. %sCopyright (C) 1988, 89, 90, 91, 92, 93, 94, 95, 96, 97\n\
  2297. %s\tFree Software Foundation, Inc.\n\
  2298. %sThis is free software; see the source for copying conditions.\n\
  2299. %sThere is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n\
  2300. %sPARTICULAR PURPOSE.\n\n\
  2301. %sReport bugs to <bug-gnu-utils@prep.ai.mit.edu>.\n\n",
  2302.       precede, precede, precede, precede, precede, precede);
  2303.  
  2304.   printed_version = 1;
  2305.  
  2306.   /* Flush stdout so the user doesn't have to wait to see the
  2307.      version information while things are thought about.  */
  2308.   fflush (stdout);
  2309. }
  2310.  
  2311. /* Print a bunch of information about this and that.  */
  2312.  
  2313. static void
  2314. print_data_base ()
  2315. {
  2316.   time_t when;
  2317.  
  2318.   when = time ((time_t *) 0);
  2319.   printf ("\n# Make data base, printed on %s", ctime (&when));
  2320.  
  2321.   print_variable_data_base ();
  2322.   print_dir_data_base ();
  2323.   print_rule_data_base ();
  2324.   print_file_data_base ();
  2325.   print_vpath_data_base ();
  2326.  
  2327.   when = time ((time_t *) 0);
  2328.   printf ("\n# Finished Make data base on %s\n", ctime (&when));
  2329. }
  2330.  
  2331. /* Exit with STATUS, cleaning up as necessary.  */
  2332.  
  2333. void
  2334. die (status)
  2335.      int status;
  2336. {
  2337.   static char dying = 0;
  2338.  
  2339.   if (!dying)
  2340.     {
  2341.       int err;
  2342.  
  2343.       dying = 1;
  2344.  
  2345.       /* Try to move back to the original directory.  This is essential on
  2346.      MS-DOS (where there is really only one process), and on Unix it
  2347.      puts core files in the original directory instead of the -C
  2348.      directory.  */
  2349.       if (directory_before_chdir != 0)
  2350.     chdir (directory_before_chdir);
  2351.  
  2352.       if (print_version_flag)
  2353.     print_version ();
  2354.  
  2355.       /* Wait for children to die.  */
  2356.       for (err = status != 0; job_slots_used > 0; err = 0)
  2357.     reap_children (1, err);
  2358.  
  2359.       /* Let the remote job module clean up its state.  */
  2360.       remote_cleanup ();
  2361.  
  2362.       /* Remove the intermediate files.  */
  2363.       remove_intermediates (0);
  2364.  
  2365.       if (print_data_base_flag)
  2366.     print_data_base ();
  2367.  
  2368.       log_working_directory (0);
  2369.     }
  2370.  
  2371.   exit (status);
  2372. }
  2373.  
  2374. /* Write a message indicating that we've just entered or
  2375.    left (according to ENTERING) the current directory.  */
  2376.  
  2377. void
  2378. log_working_directory (entering)
  2379.      int entering;
  2380. {
  2381.   static int entered = 0;
  2382.   char *message = entering ? "Entering" : "Leaving";
  2383.  
  2384.   /* Print nothing without the flag.  Don't print the entering message
  2385.      again if we already have.  Don't print the leaving message if we
  2386.      haven't printed the entering message.  */
  2387.   if (! print_directory_flag || entering == entered)
  2388.     return;
  2389.  
  2390.   entered = entering;
  2391.  
  2392.   if (print_data_base_flag)
  2393.     fputs ("# ", stdout);
  2394.  
  2395.   if (makelevel == 0)
  2396.     printf ("%s: %s ", program, message);
  2397.   else
  2398.     printf ("%s[%u]: %s ", program, makelevel, message);
  2399.  
  2400.   if (starting_directory == 0)
  2401.     puts ("an unknown directory");
  2402.   else
  2403.     printf ("directory `%s'\n", starting_directory);
  2404. }
  2405.